package com.itheima.web.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.*;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Component
public class UserManager {

    @Reference
    private AnalysisByDayService analysisByDayService;
    @Reference
    private UserInfoService userInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Reference
    private UserService userService;

    /**
     * 查询用户列表
     *
     * @param page     页码
     * @param pagesize 每页条数
     * @return
     */
    public PageBeanVo findUserList(Integer page, Integer pagesize) {
        //查询所有用户
        return userInfoService.findUserList(page, pagesize);
    }

    /**
     * 查询用户详细信息
     *
     * @param userId 用户id
     * @return 用户对象
     */
    public UserInfo finUserInfoById(Long userId) {
        return userInfoService.findById(userId);
    }

    /**
     * 查询用户视频列表
     *
     * @param page 页码
     * @param pageSize 每页条数
     * @param uid 用户id
     * @return
     */
    @Reference
    private VideoService videoService;

    //张斌鉴
    public UserInfoVo finUserInfoById1(Long userID) {
        UserInfo userInfo = userInfoService.findById(userID);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);
        String phone = userService.userIdByPhone(userID);
        Boolean aBoolean = stringRedisTemplate.hasKey(ConstantUtil.FREEZE_USER + phone);
        Boolean aBoolean1 = stringRedisTemplate.hasKey(ConstantUtil.FREEZE_USERComment + phone);
        Boolean aBoolean2 = stringRedisTemplate.hasKey(ConstantUtil.FREEZE_USERMovement + phone);
        if (!aBoolean && !aBoolean1 && !aBoolean2) {
            userInfoVo.setUserStatus("1");
        } else {
            userInfoVo.setUserStatus("2");
        }
        return userInfoVo;
    }

    public PageBeanVo finUserVideoList(Integer page, Integer pageSize, Long uid) {
        //查询用户视频列表
        PageBeanVo vo = videoService.findUserVideoList(page, pageSize, uid);
        //获取视频集合对象
        List<Video> items = (List<Video>) vo.getItems();
        //构建新的页面返回对象
        List<VideoVo> videoVoList = new ArrayList<>();
        //遍历视频集合,进行数据转移
        if (CollectionUtil.isNotEmpty(items)) {
            for (Video video : items) {
                VideoVo videoVo = new VideoVo();
                UserInfo userInfo = userInfoService.findById(video.getUserId());
                BeanUtil.copyProperties(userInfo, videoVo);
                BeanUtil.copyProperties(video, videoVo);
                videoVo.setSignature(video.getText());
                videoVo.setCover(video.getPicUrl());
                videoVoList.add(videoVo);
            }
        }
        vo.setItems(videoVoList);
        return vo;
    }


    /**
     * 首页数据显示
     *
     * @return 日志分析数据
     */
    public AnalysisSummaryVo summary() {

        return analysisByDayService.summary();
    }

    @Reference
    private MovementService movementService;

    /**
     * 查询用户动态
     *
     * @param page     页码
     * @param pageSize 每页条数
     * @param uid      用户id
     * @param state    账号状态
     * @return
     */
    public PageBeanVo findMovementListByUid(Integer page, Integer pageSize, Long uid, Integer state) {
        //查询用户的动态列表
        PageBeanVo vo = movementService.findMovementByUidAndState(page, pageSize, uid, state);
        //构建返回对象集合
        List<MovementVo> vos = new ArrayList<>();
        //获取动态集合
        List<Movement> items = (List<Movement>) vo.getItems();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                MovementVo movementVo = new MovementVo();
                UserInfo userInfo = userInfoService.findById(movement.getUserId());
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                movementVo.setCreateDate(dateFormat.format(new Date(movement.getCreated())));
                vos.add(movementVo);
            }
        }
        vo.setItems(vos);
        return vo;
    }

    /**
     * 查询动态详情
     *
     * @param movementId 动态id
     * @return 动态详情对象
     */
    public MovementVo findMovementById(String movementId) {
        //根据动态id查询动态信息
        Movement movement = movementService.findMovement(movementId);
        //构建返回对象
        MovementVo movementVo = new MovementVo();
        //进行数据转移
        if (movement != null) {
            UserInfo userInfo = userInfoService.findById(movement.getUserId());
            movementVo.setUserInfo(userInfo);
            movementVo.setMovement(movement);
            //自己处理一下时间
            movementVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(movement.getCreated())));

        }
        return movementVo;
    }

    @Reference
    private CommentService commentService;

    /**
     * 查询动态评论列表
     *
     * @param page      页码
     * @param pageSize  每页条数
     * @param messageID 动态id
     * @return pageBeanVo对象
     */
    public PageBeanVo findCommentByMovementId(Integer page, Integer pageSize, String messageID) {
        //根据动态id查询评论列表
        PageBeanVo commentList = commentService.findCommentList(page, pageSize, messageID);
        //获取评论集合
        List<Comment> items = (List<Comment>) commentList.getItems();
        //构建新的页面返回对象
        List<CommentVo> voList = new ArrayList<>();
        //遍历评论集合,进行数据转移
        if (CollectionUtil.isNotEmpty(items)) {
            for (Comment comment : items) {
                CommentVo commentVo = new CommentVo();
                UserInfo userInfo = userInfoService.findById(comment.getUserId());
                BeanUtil.copyProperties(userInfo, commentVo);
                BeanUtil.copyProperties(comment, commentVo);
                commentVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(comment.getCreated())));
                voList.add(commentVo);
            }
        }
        commentList.setItems(voList);
        return commentList;
    }

    public PageBeanVo findUserList1(Integer page, Integer pageSize) {

        PageBeanVo userInfo = userInfoService.findUserInfo(page, pageSize);
        List<UserInfo> userInfoList = (List<UserInfo>) userInfo.getItems();
        List<UserInfoVo> userInfoVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userInfoList)) {
            for (UserInfo info : userInfoList) {

                UserInfoVo userInfoVo = new UserInfoVo();
                BeanUtil.copyProperties(info, userInfoVo);


                //获取redis里所有的的FREEZE_USER键
                String phone = userService.userIdByPhone(userInfoVo.getId());
                Boolean aBoolean = stringRedisTemplate.hasKey(ConstantUtil.FREEZE_USER + phone);
                Boolean aBoolean1 = stringRedisTemplate.hasKey(ConstantUtil.FREEZE_USERComment + phone);
                Boolean aBoolean2 = stringRedisTemplate.hasKey(ConstantUtil.FREEZE_USERMovement + phone);
                if (!aBoolean && !aBoolean1 && !aBoolean2) {
                    userInfoVo.setUserStatus("1");
                } else {
                    userInfoVo.setUserStatus("2");
                }
                userInfoVoList.add(userInfoVo);


            }
        }
        userInfo.setItems(userInfoVoList);
        return userInfo;
    }

    public Map<String, String> freeze(Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        String phone = userService.userIdByPhone(userId.longValue());
        Duration duration = Duration.ofDays(5);
        if (freezingTime == 1) {
            duration = Duration.ofDays(3);
        } else if (freezingTime == 2) {
            duration = Duration.ofDays(7);
        } else if (freezingTime == 3) {
            if (freezingRange == 1) {
                stringRedisTemplate.opsForValue().set(ConstantUtil.FREEZE_USER + phone, reasonsForFreezing);
            } else if (freezingRange == 2) {
                stringRedisTemplate.opsForValue().set(ConstantUtil.FREEZE_USERComment + phone, reasonsForFreezing);
            } else if (freezingRange == 3) {
                stringRedisTemplate.opsForValue().set(ConstantUtil.FREEZE_USERMovement + phone, reasonsForFreezing);
            }
        }
        if (freezingRange == 1) {
            stringRedisTemplate.opsForValue().set(ConstantUtil.FREEZE_USER + phone, reasonsForFreezing, duration);
        } else if (freezingRange == 2) {
            stringRedisTemplate.opsForValue().set(ConstantUtil.FREEZE_USERComment + phone, reasonsForFreezing, duration);
        } else if (freezingRange == 3) {
            stringRedisTemplate.opsForValue().set(ConstantUtil.FREEZE_USERMovement + phone, reasonsForFreezing, duration);
        }
        Map<String, String> map = new HashMap<>();
        map.put("message", "mock: 操作成功");
        return map;

    }

    public Map unfreeze(Integer userId) {
        String phone = userService.userIdByPhone(userId.longValue());
        stringRedisTemplate.delete(ConstantUtil.FREEZE_USER + phone);
        stringRedisTemplate.delete(ConstantUtil.FREEZE_USERComment + phone);
        stringRedisTemplate.delete(ConstantUtil.FREEZE_USERMovement + phone);
        Map<String, String> map = new HashMap<>();
        map.put("message", "mock: 操作成功");
        return map;
    }

    /**
     * 在首页中，根据时间显示图标数据: 新用户 活跃用户  次日留存。这些数据是需要基于用户的操作来进行统计
     */
    public Map findDashboard(String sd, String ed, String type) {
        //开始时间日期转换
        String sdDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.valueOf(sd)));
        DateTime sdTime = DateUtil.parse(sdDate);
        //结束日期转换
        String edDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.valueOf(ed)));
        DateTime edTime = DateUtil.parse(edDate);
        //今年的数据
        List thisYear = analysisByDayService.findDashboard(sdDate, edDate, type);
        //上一年的数据
        String lastSdTime = DateUtil.offset(sdTime, DateField.YEAR, -1).toDateStr();
        String lastEdTime = DateUtil.offset(edTime, DateField.YEAR, -1).toDateStr();
        List lastYear = analysisByDayService.findDashboard(lastSdTime, lastEdTime, type);
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("thisYear", thisYear);
        hashMap.put("lastYear", lastYear);
        return hashMap;
    }
}
